<?php
class portMod extends commonMod {
    //更新酒店时间，在线
    public function  updateHotelState($ip,$hotel){
    	set_time_limit(0);
        $time=time();
        $list = $this->model->query("select * from `h_hotels` where hotelName='{$hotel}' and ipaddr='{$ip}'");
		if($list){
			$row=$this->model->query("UPDATE `h_hotels` SET `stime`='{$time}' WHERE id=".$list[0]['id']);
			$this->testVpn($ip,$list[0],$list[0]['vpnstate']);
		}
        return 1;
    }
    public function callbackData(){
        $data=$_GET['data']?$_GET['data']:1;
        $a=json_decode($data);

        $return_code= $a->return_code;
        if($return_code!='SUCCESS'){
            $return_msg= $a->return_msg;
            $result='{"result":"false","msg":"'.$return_msg.'"}';
        }else{
            $result_code= $a->result_code;
            if($result_code!='SUCCESS'){
                $err_code= $a->err_code;
                $err_code_des= $a->err_code_des;
                $result='{"result":"false","msg":"'.$err_code.':'.$err_code_des.'"}';
            }else{
                $openid= $a->openid;
                $is_subscribe= $a->is_subscribe;
                $out_trade_no= $a->out_trade_no;
                $transaction_id= $a->transaction_id;

                $attach= $a->attach;
                $attachArry=explode('/',$attach);
                $hotel=$attachArry[0];
                $room=$attachArry[1];
                $guestname=$attachArry[2]?$attachArry[2]:0;
                $guestpid=$attachArry[3]?$attachArry[3]:0;
                $filmname=$attachArry[4];
                $filmprice=$attachArry[5];
                $time=$attachArry[6];
                $typeStr=$attachArry[10];
                $typeArr=explode("_",$typeStr);
                $account=$typeArr[1];
                $type=$typeArr[2];

                $row=$this->model->query("SELECT * FROM `h_filmorder` WHERE ordernum='".$out_trade_no."'");
                if(!$row){
                    $row=$this->model->query("SELECT * FROM `h_hotels` WHERE hotelName='".$hotel."'");
                    if($row){
                        $ip=$row[0]['ipaddr'];
                    }
                    $sql="INSERT INTO `h_filmorder`(`ordernum`, `hotelName`, `roomNo`, `guestName`, `guestPid`,  `stime`, `filename`, `price`, `state`,  `openid`, `is_subscribe`, `transaction_id`, `ip`, `attach`, `account`,`type`) VALUES ('{$out_trade_no}','{$hotel}','{$room}','{$guestname}','{$guestpid}','{$time}','{$filmname}','{$filmprice}','0','{$openid}','{$is_subscribe}','{$transaction_id}','0','{$attach}','{$account}','{$type}')";
                    $row=$this->model->query($sql);
                    if($row){
                        $result='{"result":"success","msg":"'.$attach.'","order":"'.$out_trade_no.'"}';
                    }
                }

            }
        }

        if($result){
            $da= "http://".$ip."/".$hotel."/portmovie/movieResult?result=".$result;
            file_get_contents($da);
        }
    }

    public function xsmovieTime(){
        $Upload=$_POST['Upload']?$_POST['Upload']:1;
        $clientViewTime=json_decode($Upload);

        if($clientViewTime){
            $ip= $clientViewTime->ip;
            $hotel= $clientViewTime->hotel;
            $data_json=$clientViewTime->data_json;

            $sql="select * from h_hotels where hotelName='".$hotel."' and ipaddr='".$ip."'";
            $row=$this->model->query($sql);
            if($row){
                $id=$row[0]['id'];
//                $hotel=$row[0]['hotel'];
                $operationStatus=$row[0]['operationStatus'];
                $time=date('Y-m-d',time());
                if($data_json){

                    $sqlval='';
                    foreach($data_json as $val){
                        $name=$val->name;
                        $menu=$val->menu;
                        $num=$val->num;
                        $length=$val->length;
                        $uptime=$val->uptime;
                        $sqlval=$sqlval."('{$id}','{$num}','{$length}','{$name}','{$menu}','{$uptime}','{$operationStatus}'),";
                    }
                    $sqlval=substr($sqlval,0,-1);
                    $sql="INSERT INTO `h_hotels_data_movieday`( `hotelid`,  `count`, `duration`, `moviename`, `moviemenu`,  `stime`, `operationStatus`) VALUES ".$sqlval;

                    $row=$this->model->query($sql);
                }

                $result='{"result":"xsmovieTime"}';
                echo $result;
            }
        }
    }
    public function clientViewTime(){
        $Upload=$_POST['Upload']?$_POST['Upload']:1;
        $clientViewTime=json_decode($Upload);

        if($clientViewTime){
            $ip= $clientViewTime->ip;
            $hotel= $clientViewTime->hotel;
            $data_json=$clientViewTime->data_json;
            $clientNoPms=$clientViewTime->clientNoPms;
            $clientNoStv=$clientViewTime->clientNoStv;
//            $startTvTotallength=$clientViewTime->startTvTotallength;

            $sql="select * from h_hotels where hotelName='".$hotel."' and ipaddr='".$ip."'";
            $row=$this->model->query($sql);
            if($row){
                $id=$row[0]['id'];
                $hotel=$row[0]['hotel'];
                $clientNoPc=$row[0]['clientNoPc'];
                $clientNoXS=$row[0]['clientNo'];
                $clientNoTv=$row[0]['clientNoTv'];
                $operationStatus=$row[0]['operationStatus'];
                $time=date('Y-m-d',time());

                if($clientNoPms){
                    foreach($clientNoPms as $valPms){
                        $clientNo=$valPms->clientNo;
                        $platform_name=$valPms->platform_name;
                        if($platform_name=='云-PC'){
                            $platform_name='PC';
                            $clientNoTotalPms=$clientNoPc;
                        }else if($platform_name=='通用'||$platform_name=='小帅投影仪'||$platform_name==''){
                            $platform_name='XS';
                            $clientNoTotalPms=$clientNoXS;
                        }else{
                            $platform_name='TV';
                            $clientNoTotalPms=$clientNoTv;
                        }
                        $timePms=$valPms->uptime;
                        $level=$valPms->level;
                        $durationPms=$valPms->duration;
                        if($clientNo){
                            $rowSP=$this->model->query("SELECT * FROM `h_hotels_data` WHERE hotelid='{$id}' and stime='{$timePms}' and deviceType='{$platform_name}' and dataType='Pms' and dataLevel='{$level}'");
                            if($rowSP){
                                $clientNoper=$rowSP[0]['clientNo'];
                                $totalLengthper=$rowSP[0]['totalLength'];
                                $idper=$rowSP[0]['id'];
                                if(($clientNoper<$clientNo)){
                                    $clientNonow=$clientNo;
                                }else{
                                    $clientNonow=$clientNoper;
                                }
                                if($durationPms){
                                    $totalLengthnow=$durationPms+$totalLengthper;
                                }else{
                                    $totalLengthnow=$totalLengthper;
                                }
                                $occupancyRate=100*$clientNonow/$clientNoTotalPms;
                                $this->model->query("UPDATE `h_hotels_data` SET `clientNo`='{$clientNonow}',`totalLength`='{$totalLengthnow}',`occupancyRate`='{$occupancyRate}' WHERE id=".$idper);
                             }else{
                                $occupancyRate=100*$clientNo/$clientNoTotalPms;
                                $sqlCNo="INSERT INTO `h_hotels_data`( `hotelid`, `hotel`,   `stime`, `clientNo`, `totalLength`,`deviceType`, `dataType`, `dataLevel`, `operationStatus`,`occupancyRate`) VALUES('{$id}','{$hotel}','{$timePms}','{$clientNo}','{$durationPms}','{$platform_name}','Pms','{$level}','{$operationStatus}','{$occupancyRate}')";
                                $row=$this->model->query($sqlCNo);
                            }
                        }
                    }
                }
                if($clientNoStv){
                    foreach($clientNoStv as $valStv){
                        $clientNo=$valStv->clientNo;
                        $platform_name=$valStv->platform_name;
                        if($platform_name=='云-PC'){
                            $platform_name='PC';
                            $clientNoTotalStv=$clientNoPc;
                        }else if($platform_name=='通用'||$platform_name=='小帅投影仪'||$platform_name==''){
                            $platform_name='XS';
                            $clientNoTotalStv=$clientNoXS;
                        }else{
                            $platform_name='TV';
                            $clientNoTotalStv=$clientNoTv;
                        }
                        $timeStv=$valStv->uptime;
                        $durationStv=$valStv->duration;
                        $timeS=$timeStv?$timeStv:$time;
                        $level=$valStv->level;
                        if($clientNo){
                            $rowST=$this->model->query("SELECT * FROM `h_hotels_data` WHERE hotelid='{$id}' and stime='{$timeS}' and deviceType='{$platform_name}' and dataType='Stv' and dataLevel='{$level}'");
                             if($rowST){
                                $clientNoper=$rowST[0]['clientNo'];
                                $totalLengthper=$rowST[0]['totalLength'];
                                $idper=$rowST[0]['id'];
                                if(($clientNo)){
                                    $clientNonow=$clientNo+$clientNoper;
                                }else{
                                    $clientNonow=$clientNoper;
                                }
                                if($durationStv){
                                    $totalLengthnow=$durationStv+$totalLengthper;
                                }else{
                                    $totalLengthnow=$totalLengthper;
                                }
                                 $occupancyRate=100*$clientNonow/$clientNoTotalStv;
                                $this->model->query("UPDATE `h_hotels_data` SET `clientNo`='{$clientNonow}',`totalLength`='{$totalLengthnow}',`occupancyRate`='{$occupancyRate}' WHERE id=".$idper);
                             }else{
                                 $occupancyRate=100*$clientNo/$clientNoTotalStv;
                                $sqlCNo="INSERT INTO `h_hotels_data`( `hotelid`, `hotel`,   `stime`, `clientNo`, `totalLength`,`deviceType`, `dataType`, `dataLevel`, `operationStatus`,`occupancyRate`) VALUES('{$id}','{$hotel}','{$timeS}','{$clientNo}','{$durationStv}','{$platform_name}','Stv','{$level}','{$operationStatus}','{$occupancyRate}')";
                                $row=$this->model->query($sqlCNo);
                            }
                        }
                    }
                }

                if($data_json){

                    $sqlval='';
                    foreach($data_json as $val){
                        $duration=$val->duration;
                        $package=$val->package;
                        $apkName=$val->apkName;
                        $apktime=$val->uptime;
                        if($duration){
                            $sqlval=$sqlval."('{$id}','{$duration}','{$package}','{$apkName}','{$apktime}','{$operationStatus}'),";
                        }
                    }
                    $sqlval=substr($sqlval,0,-1);
                    $sql="INSERT INTO `h_hotels_data_apk`( `hotelid`,`duration`, `package`, `apkName`, `stime`, `operationStatus`) VALUES ".$sqlval;
                    $row=$this->model->query($sql);
                }

                $result='{"result":"clientViewTime"}';
                echo $result;
            }
        }
    }

    public function clientTourTime(){
        $Upload=$_POST['TourTime']?$_POST['TourTime']:1;
//        echo $Upload;
         $clientViewTime=json_decode(trim($Upload));
        if($clientViewTime){
            $ip= $clientViewTime->ip;
            $hotel= $clientViewTime->hotel;

            $tourRooms=$clientViewTime->tourRooms;
            $tourTotal=$clientViewTime->tourTotal;
            $json_Total=$clientViewTime->json_Total;

            $sql="select * from h_hotels where hotelName='".$hotel."' and ipaddr='".$ip."'";
            $row=$this->model->query($sql);
            if($row){
                $id=$row[0]['id'];
                $hotel=$row[0]['hotel'];
                $time=date('Y-m-d',time());

//                $sqls="SELECT * FROM `h_hotels_data` WHERE hotelid=".$id." and stime='".$time."'";
//                $rows=$this->model->query($sqls);
//                if($rows){
//                    $rid=$rows[0]['id'];
//                    $sqlu="UPDATE `h_hotels_data` SET `tourRooms`='{$tourRooms}',`tourTotal`='{$tourTotal}' WHERE id=".$rid;
//                }else{
//                    $sqlu="INSERT INTO `h_hotels_data`( `hotelid`, `hotel`,   `stime`, `tourRooms`, `tourTotal`) VALUES ('{$id}','{$hotel}','{$time}','{$tourRooms}','{$tourTotal}')";
//                }
//
//                $row=$this->model->query($sqlu);

                if($json_Total){
                    foreach($json_Total as $key=>$var){
                        $flag=$key;
                        for($i=0;$i<10;$i++){
                            $data_name=$var[$i]->name;
                            $data_num=$var[$i]->num;
                            $sqlv="INSERT INTO `h_ranking`( `hotelid`, `flag`, `uploaddate`, `data_name`, `data_num`) VALUES ('{$id}','{$flag}','{$time}','{$data_name}','{$data_num}')";
                            $row=$this->model->query($sqlv);
                        }
                    }
                }
                $result='{"result":"clientTourTime"}';
                echo $result;
            }
        }
    }
public function hotelInfo(){
    $data=$_POST['data']?$_POST['data']:1;

    $systemInfo=json_decode($data);
    if($systemInfo){
        $ip= $systemInfo->ip;
        $hotel= $systemInfo->hotel;
        $count= $systemInfo->count;
        $us= $systemInfo->us;
        $sy= $systemInfo->sy;

        $list = $this->model->query("select * from `h_hotels` where hotelName='{$hotel}' and ipaddr='{$ip}'");
        if($list){
            $sql="UPDATE `h_hotels` SET `cpu`='".$us.$sy."',`stime`='".time()."' WHERE hotelName='".$hotel."' and ipaddr='".$ip."'";
            $row=$this->model->query($sql);
        	$this->testVpn($ip,$list[0],$list[0]['vpnstate']);

            $result='{"hotelName":"'.$list[0]['hotel'].'"}';
            echo $result;
        }

    }else{
        echo '333';
    }

}

    //电影分发
    public function movieDistribute(){
        $data=$_GET['data']?$_GET['data']:1;
        $a=json_decode($data);
        if($a){
            $ip= $a->ip;
            $hotel= $a->hotel;
            $task= $a->task;
            $this->updateHotelState($ip,$hotel);
        }
        switch($task){
            case 'filmShelf':
                $sql="SELECT d.* FROM `h_distribute` d left join `h_hotels` h on h.id=d.hotelid  WHERE d.state=12 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $row=$this->model->query($sql);
                if($row){
                    $row_json=json_encode($row);
                    $result='{"result":'.$row_json.'}';
                    foreach($row as $val){
                        $this->model->query("UPDATE `h_distribute` SET `state`=13 WHERE id=".$val['id']);
                    }
                }else{
                    $result='{"result":"false"}';
                }
                echo $result;
                break;
            case 'menuTask':
                $sql="SELECT d.* FROM `h_distribute` d left join `h_hotels` h on h.id=d.hotelid WHERE d.state=22 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $row=$this->model->query($sql);
                if($row){
                    $row_json=json_encode($row);
                    $result='{"result":'.$row_json.'}';
                    foreach($row as $val){
                        $this->model->query("UPDATE `h_distribute` SET `state`=23 WHERE id=".$val['id']);
                    }
                }else{
                    $result='{"result":"false"}';
                }
                echo $result;
                break;
            case 'delmovieTask':
                $sql="SELECT d.* FROM `h_distribute` d left join `h_hotels` h on h.id=d.hotelid WHERE d.state=9 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $row=$this->model->query($sql);
                if($row){
                    $row_json=json_encode($row);
                    $result='{"result":'.$row_json.'}';
                    foreach($row as $val){
                        $this->model->query("delete from h_distribute where id=".$val['id']);
                    }
                }else{
                    $result='{"result":"false"}';
                }
                echo $result;
                break;
            case 'm1905Task':
                $sql="SELECT d.id,d.moviename,d.moviesize FROM h_distribute_m1905 d left join `h_hotels` h on h.id=d.hotelid   WHERE d.state=1 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $row=$this->model->query($sql);
                if($row){
                    $row_json=json_encode($row);
                    $result='{"result":'.$row_json.'}';
                    foreach($row as $val){
                        $row=$this->model->query("UPDATE `h_distribute_m1905` SET `state`=2 WHERE id=".$val['id']);
                    }
                }else{
                    $result='{"result":"false"}';
                }
                echo $result;
                break;
            case 'priceTask':
                $sql="SELECT d.id,d.payname,d.price,d.paymode FROM p_allpaytask d left join `h_hotels` h on h.id=d.hotelid   WHERE d.state=1 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $rowAll=$this->model->query($sql);
                if($rowAll){
                    foreach($rowAll as $valAll){
                        $this->model->query("UPDATE `p_allpaytask` SET `state`=2 WHERE id=".$valAll['id']);
                    }
                }else{
                    $rowAll='false';
                }
                $rowAll_json=json_encode($rowAll);

                $sqlSingle="SELECT d.id,d.moviename,d.price,d.paymode FROM p_singletask d left join `h_hotels` h on h.id=d.hotelid   WHERE d.state=1 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $rowSingle=$this->model->query($sqlSingle);
                if($rowSingle){
                    foreach($rowSingle as $val){
                        $this->model->query("UPDATE `p_singletask` SET `state`=2 WHERE id=".$val['id']);
                    }
                }else{
                    $rowSingle='false';
                }
                $rowSingle_json=json_encode($rowSingle);
                $result='{"allpay":'.$rowAll_json.',"singlepay":'.$rowSingle_json.'}';
                echo $result;
                break;
            default:
                $sql="SELECT d.id,d.starttime,d.endtime,d.content as price,m.movie_name,m.movie_addr,m.movie_trailer,m.movie_content,m.movie_pic,m.movie_post FROM h_distribute d left join `h_hotels` h on h.id=d.hotelid left join h_movies m on d.movieid=m.id  WHERE d.state=1 and h.hotelName='".$hotel."' and h.ipaddr='".$ip."'";
                $row=$this->model->query($sql);
                if($row){
                    $row_json=json_encode($row);
                    $result='{"result":'.$row_json.'}';
                    foreach($row as $val){
                        $row=$this->model->query("UPDATE `h_distribute` SET `state`=2 WHERE id=".$val['id']);
                    }

                }else{
                    $result='{"result":"false"}';
                }
                echo $result;
                break;
        }
    }
    public function movieStatus(){
        $data=$_POST['data']?$_POST['data']:$_GET['data'];
        $data=json_decode($data);
        if($data){
            foreach($data as $a){
                $id=$a->task_id;
                $movie_download_status=$a->movie_download_status;
                $download_status=$a->download_status;
                $task= $a->task;

                switch($task){
                    case 'filmShelf':
                        $state=14;
                        $sql="UPDATE `h_distribute` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                        $row=$this->model->query($sql);
                        break;
                    case 'menuTask':
                        $state=24;
                        $sql="UPDATE `h_distribute` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                        $row=$this->model->query($sql);
                        break;
                    case 'm1905Task':
                        if($download_status){
                            if($download_status==3){
                                $state=4;
                            }else{
                                $state=3;
                            }
                            $sql="UPDATE `h_distribute_m1905` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                            $row=$this->model->query($sql);
                        }
                        break;
                    case 'priceTask':
                        $paymode= $a->paymode;
                        $state=4;
                        if($paymode=='all'){
                            $sql="UPDATE `p_allpaytask` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                            $row=$this->model->query($sql);
                        }else{
                            $sql="UPDATE `p_singletask` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                            $row=$this->model->query($sql);
                        }
                        break;
                    default:
                        if($download_status){
                            if($download_status==3){
                                $state=4;
                            }else{
                                $state=3;
                            }
                            $sql="UPDATE `h_distribute` SET `schedule`='{$movie_download_status}',`state`='{$state}' WHERE id=".$id;
                            $row=$this->model->query($sql);
                        }
                        break;
                }
            }
        }
    }

    public function roomfeeData(){
        $attach=$_GET['data']?$_GET['data']:1;
        $attachArry=explode('/',$attach);
        $hotel=$attachArry[0];
        $room=$attachArry[1];
        $guestname=$attachArry[2]?$attachArry[2]:0;
        $guestpid=$attachArry[3]?$attachArry[3]:0;
        $filmname=$attachArry[4];
        $filmprice=$attachArry[5];
        $time=$attachArry[6];
        $typeStr=$attachArry[10];
        $typeArr=explode("_",$typeStr);
        $account=$typeArr[1];
        $type=$typeArr[2];
        $out_trade_no=$attachArry[12];

        $openid=0;
        $transaction_id=0;
        $is_subscribe=0;
        $row=$this->model->query("SELECT * FROM `h_filmorder` WHERE ordernum='".$out_trade_no."'");
        if(!$row){

            $sql="INSERT INTO `h_filmorder`(`ordernum`, `hotelName`, `roomNo`, `guestName`, `guestPid`,  `stime`, `filename`, `price`, `state`, `openid`, `is_subscribe`, `transaction_id`, `ip`, `attach`, `account`,`type`) VALUES ('{$out_trade_no}','{$hotel}','{$room}','{$guestname}','{$guestpid}','{$time}','{$filmname}','{$filmprice}','0','{$openid}','{$is_subscribe}','{$transaction_id}','0','{$attach}','{$account}','{$type}')";
         //  echo $sql;
            $row=$this->model->query($sql);
            if($row){
                $result='{"result":"success","msg":"'.$attach.'","order":"'.$out_trade_no.'"}';
            }
        }
    }


    public function callbackDataAlipay(){
        $attach=$_GET['data']?$_GET['data']:1;
        $a=json_decode($attach);

        $openid= $a->open_id;
        $subject= $a->subject;
        $out_trade_no= $a->out_trade_no;
        $total_amount= $a->total_amount;
        $trade_no= $a->trade_no;

        $contentArr=explode("_",$out_trade_no);
        $date=$contentArr[0];
        $hotel=$contentArr[1];
        $rname=$contentArr[2];
        $ID=$contentArr[3];
        $type=$contentArr[4];
        if($type=='a'){
            $type='all';
        }else{
            $type='single';
        }

        $time=strtotime($date);
        $filmname=str_replace("电影：","",$subject);
        $is_subscribe='';
        $account='alipay';
        $guestname='';
        $guestpid='';
        $attach='';


        $row=$this->model->query("SELECT * FROM `h_filmorder` WHERE ordernum='".$out_trade_no."'");
        if(!$row){
            $row=$this->model->query("SELECT * FROM `h_hotels` WHERE hotelName='".$hotel."'");
            if($row){
                $ip=$row[0]['ipaddr'];
            }
            $sql="INSERT INTO `h_filmorder`(`ordernum`, `hotelName`, `roomNo`, `guestName`, `guestPid`,  `stime`, `filename`, `price`, `state`,  `openid`, `is_subscribe`, `transaction_id`, `ip`, `attach`, `account`,`type`) VALUES
            ('{$out_trade_no}','{$hotel}','{$rname}','{$guestname}','{$guestpid}','{$time}','{$filmname}','{$total_amount}','0','{$openid}','{$is_subscribe}','{$trade_no}','0','{$attach}','{$account}','{$type}')";
            $row=$this->model->query($sql);
            if($row){
                $result='{"result":"success","type":"alipay","out_trade_no":"'.$out_trade_no.'","filmname":"'.$filmname.'","total_amount":"'.$total_amount.'"}';
            }
        }


        if($result){
            $da= "http://".$ip."/".$hotel."/portmovie/movieResult?result=".$result;
            file_get_contents($da);
        }
    }

    //电影 按周存储数据
    public function moviedataWeek(){
        $row=$this->model->query("SELECT  `hotelid`,`operationStatus` , SUM(  `count` ) AS c, SUM(  `duration` ) AS d,  `moviename` ,  `moviemenu` , DATE_FORMAT(stime,  '%X-%V' ) AS yearWeek, stime , SUBDATE( stime, DATE_FORMAT( stime,  '%w' ) ) AS startWeek ,
        SUBDATE( stime, DATE_FORMAT( stime,  '%w' ) -6 ) AS endWeek FROM  `h_hotels_data_movieday` WHERE rstate =0 GROUP BY hotelid, yearWeek , moviename  ");
//        var_dump($row);
        if($row){
            foreach($row as $var){
                $hotelid=$var['hotelid'];
                $operationStatus=$var['operationStatus'];
                $count=$var['c'];
                $duration=$var['d'];
                $moviename=$var['moviename'];
                $moviemenu=$var['moviemenu'];
                $yearWeek=$var['yearWeek'];
                $startWeek=$var['startWeek'];
                $endWeek=$var['endWeek'];
                $rowsWeek=$this->model->query("SELECT `id`,`count`,`duration`  FROM `h_hotels_data_movieweek` WHERE `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and `weekNo`='{$yearWeek}'");

                if($rowsWeek){
                    $weedid=$rowsWeek[0]['id'];
                    $durationNew=$rowsWeek[0]['duration']+$duration;
                    $countNew=$rowsWeek[0]['count']+$count;
                    $r=$this->model->query("UPDATE `h_hotels_data_movieweek` SET `count`='{$countNew}',`duration`='{$durationNew}' WHERE id=".$weedid);
                }else{
                    //select subdate(curdate(),date_format(curdate(),'%w')-1)//获取当前日期在本周的周一
                    //select subdate(curdate(),date_format(curdate(),'%w')-7)//获取当前日期在本周的周日
                    $r=$this->model->query("INSERT INTO `h_hotels_data_movieweek`( `hotelid`, `count`, `duration`, `moviename`, `moviemenu`,  `stime`, `etime`, `weekNo`,operationStatus) VALUES ('{$hotelid}','{$count}','{$duration}','{$moviename}','{$moviemenu}','{$startWeek}','{$endWeek}','{$yearWeek}','{$operationStatus}')");
                }
//                var_dump($r);
                if($r){
                    $this->model->query("UPDATE `h_hotels_data_movieday` SET `rstate`=1 WHERE rstate=0 and `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and DATE_FORMAT( stime,  '%X-%V' )='{$yearWeek}'");
                }
            }
        }
        exit;
    }

    //电影 按月存储数据
    public function moviedataMonth(){
        $row=$this->model->query("SELECT  `hotelid` ,`operationStatus`, SUM(  `count` ) AS c, SUM(  `duration` ) AS d,  `moviename` ,  `moviemenu` , DATE_FORMAT( stime,  '%Y-%m' ) AS yearMonth  FROM  `h_hotels_data_movieday` WHERE rstate =1 GROUP BY hotelid,yearMonth , moviename ");
//        var_dump($row);
        if($row){
            foreach($row as $var){
                $hotelid=$var['hotelid'];
                $operationStatus=$var['operationStatus'];
                $count=$var['c'];
                $duration=$var['d'];
                $moviename=$var['moviename'];
                $moviemenu=$var['moviemenu'];
                $yearMonth=$var['yearMonth'];
                $rowsWeek=$this->model->query("SELECT `id`,`count`,`duration`  FROM `h_hotels_data_moviemonth` WHERE `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and `monthNo`='{$yearMonth}'");

                if($rowsWeek){
                    $weedid=$rowsWeek[0]['id'];
                    $durationNew=$rowsWeek[0]['duration']+$duration;
                    $countNew=$rowsWeek[0]['count']+$count;
                    $r=$this->model->query("UPDATE `h_hotels_data_moviemonth` SET `count`='{$countNew}',`duration`='{$durationNew}' WHERE id=".$weedid);
                }else{
                    $r=$this->model->query("INSERT INTO `h_hotels_data_moviemonth`( `hotelid`, `count`, `duration`, `moviename`, `moviemenu`,   `monthNo`,operationStatus) VALUES ('{$hotelid}','{$count}','{$duration}','{$moviename}','{$moviemenu}','{$yearMonth}','{$operationStatus}')");
                }
//                var_dump($r);
                if($r){
                    $this->model->query("UPDATE `h_hotels_data_movieday` SET `rstate`=2 WHERE rstate=1 and `hotelid`='{$hotelid}' and `moviename`='{$moviename}' and DATE_FORMAT( stime,'%Y-%m')='{$yearMonth}'");
                }
            }
        }
        exit;
    }
    /*
     * 运维数据存储(重启、掉线、重连、首次上传数据、其他运维信息）
    * mc@2016年11月30日
    */
    public function getOperation(){
    	if(!isset($_POST['ip'])||!isset($_POST['hotel'])||!isset($_POST['operinfo'])||!isset($_POST['roomInfo'])){
    		echo '{"result":false}';
    		exit;
    	}
    	$ip = urldecode($_POST['ip']);
    	$hotel = urldecode($_POST['hotel']);
    	$operinfo = urldecode($_POST['operinfo']);
    	$roomInfo = json_decode($_POST['roomInfo'],true);
    	$hotelids = $this->model->query("SELECT * FROM `h_hotels` WHERE `hotelName` = '".$hotel."' AND `ipaddr` = '".$ip."'");
    	if($hotelids){
    		$hotelId = $hotelids[0]['id'];
    		$hotelName = $hotelids[0]['hotel'];
    		$hotelrstate = $hotelids[0]['rstate'];
    	}else{
    		echo '{"result":false}';
    		exit;
    	}
    	$addtime = time();
    	$lastTime = 0;
    	
    	$lastoper = $this->model->query('SELECT * FROM `h_operation` WHERE `hotelId`='.$hotelId);
    	//邮件设置
    	$emaillist = $this->model->query('select * from `h_emaillist` where state=0');
    	$mail_to = array();
    	foreach($emaillist as $val){
    		$mail_to[] = $val['address'];
    	}
    	$mail_subject = '服务器运维信息提醒';
    	
	    //运维数据报警值判断
	    $noticeflag = array();
	    $noticeArr = array();
	    $noticelist = $this->model->query('SELECT * FROM `h_canshu` WHERE `name` = "operation_'.$hotelId.'" OR `name`="operation_0" ORDER BY `name`');
	    if($noticelist){
	    	for($i=0;$i<count($noticelist);$i++){
	    		$noticeArr[$noticelist[$i]['x']] = explode("@@", $noticelist[$i]['y']);
	    	}
	    }
	   
	    $mail_body= '<h1>酒店名：'.$hotelName.'-'.$hotel.',IP地址：'.$ip.',酒店ID：'.$hotelId.'</h1>';//重置
	    $data = explode(";", $operinfo);
	    foreach($data as $key=>$val){
	    	$valtmp = explode(',', trim(strstr($val,'@@'),'@@'));
	    	if(is_array($valtmp)){
	    		for($i=0;$i<count($valtmp);$i++){
	    			$name = strstr($valtmp[$i],':',true);
	    			if(!$name){
	    				continue;
	    			}
	    			$value = trim(strstr($valtmp[$i],':'),':');
	    			// 负载值单独处理  
	    			$runValue = $value;
	    			if($name=='CPU load'){
	    				$runValue = max(explode(' ',$value));
	    			}
	    			
	    			//服务信息处理
	    			if($name=='web'||$name=='mysql'){
	    				if(strlen($value)>1){
	    					$runValue = max(explode(' ',$value));
	    				}
	    				$value='正常';
	    				if($runValue>0){
	    					$noticeflag[]=$name;
	    					$mail_body_attach.= '<h1>设备<span style="color:red;">'.$name.'服务</span>异常</h1>';
	    					$value='异常';
	    				}
	    			}
	    			
	    			//重启处理
	    			if($lastoper&&stripos($name,'uptime')!==false){
	    				$tmpdata = explode(";", $lastoper[0]['data']);
	    				foreach($tmpdata as $tmpvalue){
	    					if(stripos($tmpvalue,'uptime')){
	    						$lastTime = ltrim(strstr($tmpvalue,':'),':');
	    					}
	    				}
	    				if($lastTime>$value){
	    					$mail_body .= '<h1 style="color:red;">设备重启</h1>';
	    				}
	    			}
	    			
	    			//数值处理
	    			if(strpos($value, '%')){
	    				$runValue = (float)$value/100;
	    			}else if(strpos($value,'/')){
	    				$runValue = strstr($value,'/',true)/trim(strstr($value,'/'),'/');
	    			}
	    			//判断警报值
	    			if(array_key_exists($name, $noticeArr)){
	    				switch ($noticeArr[$name][0]){
	    					//1:>=,2:<=
	    					case 1:
	    						if($runValue>=0.9*$noticeArr[$name][1]){
	    							$noticeflag[]=$name;
	    							$mail_body_attach.= '<h1>设备'.$name.'已达<span style="color:red;">'.$value.'</span></h1>';
	    							//发送短信
	    						}
	    						break;
	    					case 2:
	    						if($runValue<=1.1*$noticeArr[$name][1]){
	    							$noticeflag[]=$name;
	    							$mail_body_attach.= '<h1>设备'.$name.'已达<span style="color:red;">'.$value.'</span></h1>';
	    							//发送短信
	    						}
	    						break;
	    				}
	    			}
	    		}
	    	}
	    }
	    //rstate：0无数据  1正常 2运维数据异常
	    $stateList = array(
	    	'mustopt'    =>'',
	    	'yesopt'     =>'',
	    	'needEmail'  => 0
	    );
	    switch ($hotelrstate){
	    	case 0:
	    		$stateList['mustopt'] = '<h1 style="color:red;">服务器首次上传数据</h1>';
	    		break;
	    	case 2:
	    		$stateList['yesopt'] = '<h1>服务器数据恢复正常</h1>';
	    		break;
	    	/*
	    	case 3:
	    		$stateList['mustopt'] = '<h1 style="color:red;">设备已重连</h1>';
	    		break;
	    	*/
	    }
	    
	    if(!empty($noticeflag)){
	    	$lastArr = array();
	    	if($lastoper&&$lastoper[0]['info']){
	    		$lastArr = explode(",", $lastoper[0]['info']);
	    		$diff = array_diff($noticeflag, $lastArr);
	    		$cancel = array_diff($lastArr,$noticeflag);
	    		if(!empty($diff)){
	    			$mail_body.=$mail_body_attach;
	    			$stateList['needEmail']++;
	    		}
	    		if(!empty($cancel)){
	    			$mail_body.= '<h1>设备'.implode(",", $cancel).'已恢复正常</h1>';
	    			$stateList['needEmail']++;
	    		}
	    	}else{
	    		$mail_body.=$mail_body_attach;
	    		$stateList['needEmail']++;
	    	}
	    	$info = implode(",", $noticeflag);
	    	if($hotelrstate!=2){
	    		$this->model->query('update `h_hotels` set `rstate` = 2 where `id`='.$hotelId);
	    	}
	    }elseif($hotelrstate!=1){
	    	$info = null;
	    	$this->model->query('update `h_hotels` set `rstate` = 1 where `id`='.$hotelId);
	    	$stateList['needEmail'] ++;
	    	$mail_body.=$stateList['yesopt'];
	    }
	    if($stateList['needEmail']>0||$stateList['mustopt']){
	    	$mail_body = $stateList['mustopt'].$mail_body;
	    	$arr = module('email')->sendMail($mail_to,$mail_subject,$mail_body);//发送报警
	    }
	    //最新数据表更新数据
	    if($lastoper){
	    	$this->model->query("UPDATE `h_operation` SET `data`='{$operinfo}',`addtime`={$addtime},`info`='{$info}' WHERE `hotelId`={$hotelId}");
	    }else{
	    	$this->model->query("INSERT INTO `h_operation` (`hotelId`,`data`,`info`,`addtime`) VALUES ({$hotelId},'{$operinfo}','{$info}',{$addtime});");
	    }
	    //插入全表数据
	    $this->model->query("INSERT INTO `h_alloperation` (`hotelId`,`data`,`info`,`addtime`) VALUES ({$hotelId},'{$operinfo}','{$info}',{$addtime});");
	     
	    
	    //房间信息处理
	    $exists = $this->model->query('select * from `h_roomstate` where `hotelId` = '.$hotelId);
	    $keys = array();
	    foreach($exists as $key=>$value){
	    	$keys[] = $value['roomNo'];
	    }
	    foreach($roomInfo as $room){
	    	if(in_array($room['rname'], $keys)){
	    		$upSql ='update `h_roomstate` set `rstate` = "'.$room['rstate'].'",`state` = "'.$room['state'].'",`stime` = "'.$room['stime'].'",`addtime` = '.$addtime.' where `hotelId` = '.$hotelId.' and `roomNo` = '.$room['rname'];
				$this->model->query($upSql);
	    	}else{
	    		$insert.= '("'.$room['rname'].'","'.$room['rstate'].'","'.$room['state'].'","'.$room['stime'].'",'.$hotelId.','.$addtime.'),';
	    	}
	    }
	    $insertsql = 'insert into `h_roomstate` (`roomNo`,`rstate`,`state`,`stime`,`hotelId`,`addtime`) values '.rtrim($insert,',');
	    $this->model->query($insertsql);
	}
	//检测vpn
	public function testVpn($ip,$hotel,$stat){
		if(!pingAddress($ip)){
			$vpnstate = 1;
			$mail_subject = '服务器VPN断线';
		}else{
			$vpnstate = 0;
			$mail_subject = '服务器VPN重连';
		}
		if(($stat+$vpnstate)==1){
			$this->model->query("update `h_hotels` set `vpnstate` = ".$vpnstate."   WHERE id=".$hotel['id']);//设置异常
			$emaillist = $this->model->query('select * from `h_emaillist` where state=0');
			$mail_to = array();
			foreach($emaillist as $val){
				$mail_to[] = $val['address'];
			}
			$mail_body = '<h1>酒店名：'.$hotel['hotel'].'-'.$hotel['hotelName'].',IP地址：'.$hotel['ipaddr'].',酒店ID：'.$hotel['id'].'</h1>';
			$arr = module('email')->sendMail($mail_to,$mail_subject,$mail_body);
		}
	}
	//掉线发邮件
	public function noticeOff(){
		set_time_limit(0);
		$time = time();
		//邮件地址列表
		$emaillist = $this->model->query('select * from `h_emaillist` where state=0');
		$mail_to = array();
		foreach($emaillist as $val){
			$mail_to[] = $val['address'];
		}
		$hotels = $this->model->query('select * from `h_hotels` where vpnstate!=2');
		$noticehotels = array();
		if($hotels){
			foreach($hotels as $hotel){
				$endtime = $hotel['stime'];
				if(($time-$endtime)>900){
					$noticehotels['off'][] = $hotel;
					$this->model->query('update `h_hotels` set `vpnstate` = 2 where `id`='.$hotel['id']);//设置异常
				}
			}
		}
		if(!empty($noticehotels)){
			$mail_subject = '服务器掉线';
			if(!empty($noticehotels['off'])){
				foreach($noticehotels['off'] as $hotel){
					$mail_body = '<h1>酒店名：'.$hotel['hotel'].'-'.$hotel['hotelName'].',IP地址：'.$hotel['ipaddr'].',酒店ID：'.$hotel['id'].'</h1>';
				}
			}
			$arr = module('email')->sendMail($mail_to,$mail_subject,$mail_body);
		}
	}
	//剧透社
	public function jts(){
		$time = time();
		switch($_GET['m']){
			/*
			case 'downgid':
				$lists = json_decode($_POST['lists'],true);
				$ip = $_POST['ip'];
				$proname = $_POST['proname'];
				$flag = 0;
				for($i=0;$i<count($lists);$i++){
					//添加gid
					$exist = $this->model->query('select * from h_wxps_sends  where id='.$lists[$i]['sid']);
					if(!$exist){
						echo json_encode(array('res'=>false,'msg'=>'未找到该下载项'));
					}else{
						$flag++;
						$this->model->query('update h_wxps_sends set time='.$time.',ariagid='.$lists[$i]['gid'].',remoteid='.$lists[$i]['localid'].',zippath="'.$lists[$i]['zippath'].'"  where id='.$exist[0]['id']);
						//调脚本
					}
				}
				break;
			*/
			case 'downstate':
				$lists = json_decode($_POST['lists'],true);
				$ip = $_POST['ip'];
				$proname = $_POST['proname'];
				for($i=0;$i<count($lists);$i++){
					$sid = $lists[$i]['sid'];
					$exist = $this->model->query('select * from h_wxps_sends where id='.$sid);
					if(!$exist){
						echo json_encode(array('res'=>false,'msg'=>'未找到该下载项'));
					}else{
						$send = $lists[$i];
						if(strpos($ip, ':')!==false){
							$rpcip = strstr($ip, ':',true);
						}else{
							$rpcip = $ip;
						}
						$arUrl = 'http://'.$rpcip.':6800/jsonrpc';
						$aria2 = new Aria2($arUrl);
						$statAll = $aria2->tellStatus($send['gid']);
						$stat = $statAll['result'];
						if($stat['errorCode']==0){
							if($stat['status']=='complete'){
								//$aria2->removeDownloadResult($send['ariagid']);
								$sql = 'update h_wxps_sends set state=1,time='.$time.',ariagid="'.$send['gid'].'",remoteid='.$send['localid'].',completedLength='.$stat['completedLength'].',downloadSpeed='.$stat['downloadSpeed'].',errorCode="'.$stat['errorCode'].'"  where id='.$sid;
								$this->model->query($sql);
								$vpnUrl = 'http://'.$ip.'/'.$proname.'/jts/stopAriaStat';
								$stat=jtsCurlpost($vpnUrl,array('localid'=>$send['localid']));
							}else{
								$sql = 'update h_wxps_sends set time='.$time.',ariagid="'.$send['gid'].'",remoteid='.$send['localid'].',completedLength='.$stat['completedLength'].',downloadSpeed='.$stat['downloadSpeed'].',errorCode="'.$stat['errorCode'].'"  where id='.$sid;
								$this->model->query($sql);
							}
						}else{
							$sql = 'update h_wxps_sends set state=2,time='.$time.',ariagid="'.$send['gid'].'",remoteid='.$send['localid'].',errorCode="'.$stat['errorCode'].'",state=2 where id='.$send['id'];
							$this->model->query($sql);
						}
					}
				}
				break;
		}
		exit;
	}

    //云服务器终端获取配置信息
    public function getConfig(){
        $hotelname=$_GET['hotelname'];
        $clientip=$_GET['clientip'];
        if($hotelname){
            $sql="SELECT * FROM `h_hotels` WHERE `hotelName`='{$hotelname}'";
            $row=$this->model->query($sql);
            if($row){
                $ipaddr=$row[0]['ipaddr'];
                $url = 'http://'.$ipaddr.'/serverConfig/getRoomConfig.php?clientip='.$clientip.'&hotelname='.$hotelname;
                $msg=file_get_contents($url);
                $object=json_decode($msg);
                $re=$object->result;
                if($re=='true'){
                    $project=array();
                    $msg=$object->msg;
                    foreach($msg as $k=>$v){
                        $project[$k]=$v;
                    }
                    $project['serverIp']=$ipaddr;
                    $restult='true';
                }else{
                    $restult='false';
                    $project=array(
                        "error" =>$object->msg->error
                    );
                }

            }else{
                $restult='false';
                $project=array(
                    "error" =>"此酒店尚未加入云端"
                );
            }
        }else{
            $restult='false';
            $project=array(
                "error" =>"酒店名不能为空"
            );
        }
        $restultArry=array(
            "result"=>$restult,
            "msg"=>$project
        );
        echo json_encode($restultArry);
        exit;
    }

    //更新同步酒店房间信息
    public function uploadHotelRoom(){
        $Upload=$_POST['Upload']?$_POST['Upload']:1;
//        file_put_contents('1.txt',$Upload);
//        $Upload='[{"hotel_contract":"272da7a1113e85d9","rname":"11258","ipaddr":"192.168.1.25","room_star":"3","room_type":"","room_state":"normal","room_admin":"0","room_date":"","room_id":"0","mac":"0","model":"0","platform":"0"}]';
        $data=json_decode($Upload);
        $result='{"result":"false"}';
        if($data){
            foreach ($data as $v){
                $hotel_contract = $v->hotel_contract;
                $rname = $v->rname;
                $ipaddr = $v->ipaddr;
                $room_type = $v->room_type;
                $room_star = $v->room_star;
                $room_state = $v->room_state;
                $room_admin = $v->room_admin;
                $room_date = $v->room_date;
                $room_id = $v->room_id;
                $mac = $v->mac;
                $model = $v->model;
                $platform = $v->platform;

                $rowcontract=$this->model->query("SELECT id FROM `h_hotels` WHERE `hotel_contract`='{$hotel_contract}'");
                if($rowcontract){
                    if($room_id){
                        $this->model->query("UPDATE `h_hotel_room` SET `room_key`='{$rname}',`room_number`='{$rname}',`room_star`='{$room_star}',`room_type`='{$room_type}',`room_state`='{$room_state}',`room_ip`='{$ipaddr}',`platform`='{$platform}',`mac`='{$mac}',`model`='{$model}', `synUpgradeState`=0 WHERE `hotel_contract`='{$hotel_contract}' and id=".$room_id);
                    }else{
                        $sql = "INSERT INTO `h_hotel_room`( `hotel_contract`, `room_key`, `room_number`, `room_star`, `room_type`, `room_state`,  `room_ip`, `platform`, `mac`, `model`, `addtime`, `addadminId`) VALUES('{$hotel_contract}','{$rname}','{$rname}','{$room_star}','{$room_type}','{$room_state}','{$ipaddr}','{$platform}','{$mac}','{$model}','{$room_date}','{$room_admin}')";
                        $this->model->query($sql);
                        $room_id = $this->model->insert_id();
                    }
                    $result='{"result":"true","room_id":"'.$room_id.'"}';
                }
            }
        }
        echo $result;
    }

}
function trimArray($str){
	return trim($str,',');
}
function trimall($str){
	$search = array(" ","　","\n","\r","\t");
	$replace = array("","","","","");
	return strtolower(str_replace($search, $replace, $str));
}
function pingAddress($address){
	$address = strstr($address,':')?strstr($address,':',true):$address;
	$status = -1;
	if (strcasecmp(PHP_OS, 'WINNT') === 0) {
		$pingresult = exec("ping -n 5 {$address}", $outcome, $status);
	}elseif(strcasecmp(PHP_OS, 'Linux') === 0) {
		$pingresult = exec("ping -c 5 {$address}", $outcome, $status);
	}
	if($status==0){
		$status = true;
	}else{
		$status = false;
	}
	return $status;
}
//curl_post
function jtsCurlpost($url,$post){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}
?>
